Function: (1) In programming, a named section of a program that performs a specific task. In this sense, a function is a type of procedure or routine. Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. (2) The term function is also used synonymously with operation and command. For example, you execute the delete function to erase a word.
Functions are an essential ingredient of all programs, large and small, and serve as our primary medium to express computational processes in a programming language. Fundamentally, the qualities of good functions all reinforce the idea that functions are abstractions.
It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:
These guidelines improve the readability of code, reduce the number of errors, and often minimize the total amount of code written. Decomposing a complex task into concise functions is a skill that takes experience to master. Fortunately, Python provides several features to support your efforts.
How do we square a number? (Lets pretend we do not all have calculators, phones or computers to do this for us!)
In [2]:
6 * 6
Out[2]:
The square is just a number multiplied by itself. In python the code that as:
In [3]:
6**2
Out[3]:
We can also assign this calculation to a varaible:
In [4]:
a = 6**2
What happens if we need to square different numbers in our hypothetical program?
In [5]:
a = 6**2
b = 7**2
print(a)
print(b)
What if I want to square a varaible x and set it equal to a? What if we want to square the variable y and set it equal to b?
This takes the code to a single level of abstraction
In [ ]:
x = 6
y = 7
a = x**2
b = y**2
print(a)
print(b)
We see that we are executing the same code but with a different input, x or y. We have abstracted the code a little to introduce the varaibles x and y.
How do we convert this to a function?
What is the pattern we see in the code above?
initialize a varaible
x = 6
square the varaible and set the result equal to another variable
a = x**2
print the resulting varaible
print(a)
We perform the same pattern again by replacing a with b and x with y.
In [ ]:
x = 6
a = x**2
print(a)
How do we convert this to a function, exactly as it is?
In [6]:
def square_x():
x = 6
a = x**2
print(a)
What happens when we run this? . . . Nothing!
Functions must be called to be run. Lets call the function: to call a function, simply print its name and do open and close parentheses
In [7]:
square_x()
This function prints the number 36 only. Can call it: 'print 36' if want; need to further abstract to see power of this because have nothing in middle of parentheses (no parameters), this function works. Lets chenge the function to give parameters.
Parameters are variables that serve as input to a function. We can extract the x varaible from our code to create a parameter x.
In [8]:
def square(x):
# x = 6
a = x**2
print(a)
The parameters are then fed into the functiona t the time of the call:
In [15]:
square(square(6))
Out[15]:
No longer defining x value within function. now do this outside of function. we now have function that will square any number given to it
In our example we are printing the result of our function within hte function. What if we wanted to use the result of our function? We can change the function to return a result and tehn we can save teh result and print the result.
In [19]:
x = 3 #set "global" variable equal to 3
def square(x): #still have single parameter, x; must define a function before calling it
a = x**2
return a #return is a keyword that allows us to return the result we computed earlier (Saves the result of function into variable sqr)
square(x)
Out[19]:
Now this function has a huge boost in capability by being called to a variable
What are the requirements of a function:
Optional components:
Zero or more return variables
def function_name([parameters]):
body - some code which must be indented
[return object(s)]
Note to save functions, would create file like burkes_functions.py, this would be a text file
Lets abstract our function again and enable it to raise any number to any power.
In [ ]:
def square(x, y): #function with 2 parameters
a = x**y
return a
sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)
Does teh name square make sense any more?
In [20]:
def power(x, y): #function with 2 parameters
a = x**y
return a
sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)
In [21]:
def power(x, y): #function with 2 parameters
return x**y
sqr = power(6, 2) #must feed in both parameters when call code
print(sqr)
In [ ]:
def power(x, y=2): #removes necessity of feeding second value in when call function
a = x**y
return a
sqr = power(6) #do not need to give value for y because have defaulted it, but can define value if want to automatically override default
print(sqr)
In [22]:
help(power)
To define a function use the keyword def, as in:
In [23]:
def my_function():
"""This function prints hello""" #three double quotes around statement define a doc string
print("hello")
return
Note the use of the docstring, which will allow us to use help function: -it can also extend to multiple lines, so be as descriptive as you can
In [24]:
help(my_function) #help will tell entire description that is supplied in doc string (for ex. could put defaults here)
Help on function my_function in module main:
my_function()
This function prints hello
In [31]:
def power(x, y=2):
a = x**y
return a, x, y
sqr, num, power = power(y=6, x=3)
print(sqr)
print(sqr,num,power)
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:
In [ ]:
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)
In [ ]:
def power(x, y=2):
a = x**y
return a
sqr = power(power(2)) #i've raised 2 to the second power to get 4 and feeding 4 into power again to get squared
print(sqr)
These may help you as you begin to work with functions:
When you run ("use" or "call") a function, check these things:
In [ ]: